package com.taobao.shopcart.service.impl;


import com.taobao.base.model.RestResponse;
import com.taobao.shopcart.mapper.OrderProcessHistoryMapper;
import com.taobao.shopcart.mapper.OrderProcessMapper;
import com.taobao.shopcart.model.po.OrderProcess;
import com.taobao.shopcart.model.po.OrderProcessHistory;
import com.taobao.shopcart.service.ProcessService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ProcessServiceImpl implements ProcessService {

    @Autowired
    private OrderProcessMapper orderProcessMapper;
    @Autowired
    private OrderProcessHistoryMapper orderProcessHistoryMapper;



    @Override
    public List<OrderProcess> getProcessList(int shardIndex, int shardTotal, int count) {

        List<OrderProcess> processList = orderProcessMapper.selectListByShardIndex(shardTotal, shardIndex, count);

        return processList;
    }

    @Override
    public boolean startTask(long taskId) {
        int result = orderProcessMapper.startTask(taskId);
        return result <= 0 ? false : true;
    }

    @Override
    @Transactional
    public void saveProcessFinishStatus(long taskId, int status, String errorMsg) {

        //要更新的任务
        OrderProcess process = orderProcessMapper.selectById(taskId);
        if (process == null) {
            return;
        }
        //如果任务执行失败
        if (status == 3) {
            //更新MediaProcess表的状态
            process.setStatus(3);
            process.setFailCount(process.getFailCount() + 1);//失败次数加1
            process.setErrormsg(errorMsg);
            this.orderProcessMapper.updateById(process);
            //更高效的更新方式
//            mediaProcessMapper.update()
            //todo:将上边的更新方式更改为效的更新方式
            return;
        }


        //更新Process表的状态
        process.setStatus(2);
        process.setUpdateTime(LocalDateTime.now());
        this.orderProcessMapper.updateById(process);
        //将Process表记录插入到ProcessHistory表
        OrderProcessHistory processHistory = new OrderProcessHistory();
        BeanUtils.copyProperties(process, processHistory);
        this.orderProcessHistoryMapper.insert(processHistory);
        //从Process删除当前任务
        this.orderProcessMapper.deleteById(taskId);
    }

}
